#!/usr/bin/env python

###########################
# flashcommand
# A command line compiler for Macromedia Flash MX 2004 on Mac OS X
#
# Created by Mike Chambers
# http://www.markme.com/mesh/archives/004419.cfm
#
# Requires:
#   -python : http://www.python.org
#   -Flash MX 2004 : http://www.macromedia.com/software/flash
#
#
#TODO:
#put comments at top of jsfl that put generated date, and what it was created with
#fix timing output
#write usage output
###########################

import sys
import getopt
import os.path
import tempfile
import os
import time

#i cant get used to using 1 and 0 for booleans
false = 0
true = 1

#version number
version = ".85"
    
#main function. This is the heart of the script
def main(argv):

    outputPath = None
    export = false
    saveAndCompact = false
    publish = false
    tmpDir = None
    sourcePath = None
    remJSFL = false
    closeDocAfterComplete = false
    closeFlashAfterComplete = false
    printJSFL = false
    verbose = false
    timeout = 30
    usecs3 = True

    #valid command line pars
    params = "eho:cpd:s:fkxyjpdvt:a"

    #parse the command line params
    try:
        opts, args = getopt.getopt(argv[1:], params)   
            
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    #end try
            
    if(len(opts) < 1):
        usage()   
        sys.exit(2)
    #end if
    
    #loop through arguments and set appropriate settings
    for opt, arg in opts:                
        if opt in ("-h", "--help"):      
            usage()                     
            sys.exit()                  
        elif opt == '-e':
            export = true    
        elif opt == '-o':    
            outputPath = createAbsPath(arg)  
        elif opt == '-c':
            saveAndCompact = true  
        elif opt == '-p':
            publish = true  
        elif opt == '-d':       
            tmpDir = createAbsPath(arg)  
        elif opt == '-s':
            sourcePath = createAbsPath(arg)  
        elif opt == '-k':
            remJSFL = true 
        elif opt == '-f':
        	usecs3 = False
        elif opt == '-x':
            closeFlashAfterComplete = true
        elif opt == '-y':
            closeDocAfterComplete = true
        elif opt == '-j':
            printJSFL = true 
        elif opt == '-v':
            verbose = true
            starttime = time.clock() 
        elif opt == '-a':
            versionInfo()
            sys.exit()
        elif opt == '-t':
            #catch exception here?
            timeout = int(arg)                
        #end if
    #end for
        
    #make sure that the user specified the source path
    if(sourcePath == None):
        usage()
        sys.exit(2)
    #end if                 
                 
    #make sure that an action has been specified
    if((not export) and (not publish) and  (not saveAndCompact)):
        print "You must specify an action"
        usage()
        sys.exit(2)
    #end if             
    
    #check to see if the source file exists
    if(not os.path.isfile(sourcePath)):
        print "Source file does not exist"
        sys.exit(2)
    #end if
    
    #if output path isn't specified
    if(outputPath == None): 
        if(sourcePath[-4] == "."):
            outputPath = sourcePath[0:-3] + "swf"
        else:
            outputPath = sourcePath + ".swf"
        #end if
    #end if
       
    if(os.path.isdir(outputPath)):
        print "Output file path is a directory"
        sys.exit(2)   
    #end if
       
    #check that tmpDir exists            
    if(not tmpDir == None and not os.path.isdir(tmpDir)):
           print "Temp directory does not exist : " + tmpDir
           sys.exit(2)
    #end if         
                
    tempfile.tempdir = tmpDir          
      
    logFilePath = tempfile.mktemp() + ".log"                
                     
    jsfl = []    
    
    jsfl.append("//Generated by FlashCommand for OS X\n");
    jsfl.append("//" + time.asctime(time.gmtime()) + " UTC\n");
    jsfl.append("//http://www.mikechambers.com/blog/2004/02/20/flashcommand-flash-command-line-compiler-for-os-x/\n");
    
    jsfl.append("var sourceFile = \"" + createURI(sourcePath) + "\";\n")
    jsfl.append("var outputFile = \"" + createURI(outputPath) + "\";\n") 
    
    #code for log file
    jsfl.append("var logFile = \"" + createURI(logFilePath) + "\";\n");
    jsfl.append("var doc = fl.openDocument(sourceFile);\n");    
                
    if (saveAndCompact):
        jsfl.append("doc.saveAndCompact(false);\n")
    #end if


    jsfl.append("fl.outputPanel.clear();\n")

    if(publish):
        jsfl.append("fl.getDocumentDOM().publish();\n")
    #end if

    if(export):
        jsfl.append("doc.exportSWF(outputFile, true);\n")
        jsfl.append("fl.getDocumentDOM().testMovie();\n")
    #end if

    jsfl.append("fl.outputPanel.save(logFile, true);\n")
    
    #Thanks to Patrick Palmer who provided this fix for cs3
    if usecs3:
    	jsfl.append("fl.compilerErrors.save(logFile, true);\n")

    if(closeDocAfterComplete):
        jsfl.append("fl.getDocumentDOM().close(false);\n")
    #end if

    if(closeFlashAfterComplete):
        jsfl.append("fl.quit(false);\n")
    #end if

    if(printJSFL):
        for x in jsfl:
            print x[:-1]
            
        sys.exit()
    #end main        
    
    #write jsfl file to file
    try:
        jsflFile = open(tempfile.mktemp() + ".jsfl", "w")  
        jsflFile.writelines(jsfl)
        jsflFile.close()
    except Exception:
        print "Error creating JSFL file."
        print "Exiting"
        sys.exit(2)
    #end try        

    if(verbose):
        print "Source File : " + sourcePath
        print "Output File : " + outputPath
        
        actions = []
        
        if(export):
           actions.append("Export")
        #end if   
        
        if(saveAndCompact):
           actions.append("Save and Compact")
        #end if
        
        if(publish):
           actions.append("Public")
        #end if        
        
        for x in actions:
            aString = x + ","
        #end for    
                
        print "Actions : " + aString[:-1]        
    
        print "Save JSFL " + getBoolStr(remJSFL)
        
        if(remJSFL):
            print "JSFL File : " + jsflFile.name
        #end if 
        
        print "Close FLA : " + getBoolStr(closeDocAfterComplete)
        print "Close Flash : " + getBoolStr(closeFlashAfterComplete)
    #end if

    #write applescript pointing to file
    
    flash_name = "Adobe Flash CS3"
    
    if not usecs3:
    	flash_name = "Flash"
    
    shellCommand = "osascript -e 'tell application \""+ flash_name +"\" to open posix file \""+ jsflFile.name +"\" activate'"
    
    if(verbose):
        print "Calling Flash"
        print "Executing Command : " + shellCommand
    #end if
    
    os.system(shellCommand)
    
    #loop looking for output file to be created
    counter = 0
    while(true):
        if(verbose):
            sys.stdout.write(".")
        #end if
        
        if(os.path.isfile(logFilePath)):
            break
        #end if
        
        if(counter >= timeout):
            print ""
            print "Timeout waiting for Flash to respond (%s Seconds)" % (counter)  
            sys.exit(2)
            break
        #end if
        
        counter = counter + 1
        time.sleep(1)
    #end while
    
    print ""
    
    if(verbose):
        print "Checking Flash Output"
    #end if
    
    try:
        logFile = open(logFilePath, "r")
        logContents = logFile.read()
        logFile.close()
    except Exception:
        print "Error manipulating log file."
        print "Exiting"
        sys.exit(2)
    #end try
        

    if(len(logContents) > 0):
        print logContents.replace("\r", "\n")[12:]
    #end if
    
    try:
        print "Cleaning up temporary files"
        if(not remJSFL):
            os.remove(jsflFile.name)
        #end if
        
        os.remove(logFile.name)
    except Exception:
        print "could not delete temporary files."
        
    if(verbose):
        print "Process Complete"
        stoptime = time.clock()
        #this is giving weird results
        print "Total time : %.3f" % (stoptime - starttime)
    #end if    
    
#end main

def createAbsPath(path):
    if(path[0] == "-"):
        usage()
        sys.exit(2)
    #end if
    return os.path.abspath(path)  
#end createAbsPath

def usage():
    print """usage: flashcommand -e | -c | -p [-v] [-x] (-s <sourcefile>) ([-o] <exportpath>) ([-t] <timeout>)([-d] <tempdir>) [-j]

Options and arguments:
-a : Prints version and about information.
-c : Specifies save and compact action. 
-d : Specifies temp directory that will be used for temporary files. Optional.
-e : Specifies export action.
-h : Prints usage information.
-j : Specifies that the generated JSFL file should be printed. If this option is specified, Flash will not be executed.
-o : Specifies the output file if -e flag is also set. Optional. If not specified, file will be output to same directory as source.
-p : Specifies publish action.
-s : Specifies source file. Required.
-t : Specifies timeout value. Optional.
-v : Specifies verbose mode. Optional.
-f : Specifies that the Flash authoring version installed is a version other than Flash CS3
-x : Specifies whether Flash should be closed after it is done processing. Optional."""

#end usage
    
def versionInfo():
    print """flashcommand version %s
Created by Mike Chambers
http://www.markme.com/mesh/archives/004419.cfm""" % (version)
#end if    
    
def createURI(path):
    return "file:///" + path 
#end createURI

def getBoolStr(bool):
    if(bool):
        return "true"
    else:
        return "false"
    #end if
#end getBoolStr

main(sys.argv)
